package com.hutou.chuangke.fragmentnet;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hutou.chuangke.Bean.AdverBean;
import com.hutou.chuangke.Bean.AlbnmlistBean;
import com.hutou.chuangke.Bean.AlbumDetailBean;
import com.hutou.chuangke.Bean.SoundBean;
import com.hutou.chuangke.Bean.ItemsEntity;
import com.hutou.chuangke.Bean.LooParent;
import com.hutou.chuangke.Bean.MvlistBean;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.activity.ArtistDetailActivity;
import com.hutou.chuangke.activity.IndexAlbumDetailActivity;
import com.hutou.chuangke.activity.IndexItemActivity;
import com.hutou.chuangke.activity.IndexRecommendActivity;
import com.hutou.chuangke.activity.NewAlumsDetailActivity;
import com.hutou.chuangke.activity.SingerDetailActivity;
import com.hutou.chuangke.activity.VideoViewActivity;
import com.hutou.chuangke.adapter.IndexSoundAdapter;
import com.hutou.chuangke.fragment.AttachFragment;
import com.hutou.chuangke.info.MusicInfo;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.NetworkUtils;
import com.hutou.chuangke.net.http.HttpUrl;
import com.hutou.chuangke.service.MusicPlayer;
import com.hutou.chuangke.widget.HeightExpandableListView;
import com.hutou.chuangke.widget.MyGridview;
import com.hutou.chuangke.widget.banner.BannerPagerAdapter;
import com.kevin.loopview.AdLoopView;
import com.kevin.loopview.internal.BaseLoopAdapter;
import com.kevin.loopview.internal.LoopData;
import com.kevin.loopview.utils.JsonTool;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by tyh 2017/3/18.
 */
public class IndexFragment extends AttachFragment implements BannerPagerAdapter.OnBannerClickListener, AdapterView.OnItemClickListener, View.OnClickListener {
    private MyGridview albnmgridview,mvgridview,soundgridview;
    private AdLoopView Adloopview;
    private ScrollView scrollview;
    IndexSoundAdapter albnGridAdapter;
    IndexSoundAdapter soundGridAdapter;
    IndexSoundAdapter mvGridAdapter;

    private RelativeLayout albnm_layout,mv_layout,sound_layout;
//    private SwipeRefreshLayout swipeRefresh; //下拉刷新layout
    private BannerPagerAdapter mBannerPagerAdapter;
    private boolean isFromCache = true;

    private List<AdverBean> advers = new ArrayList<>();
    private List<AlbnmlistBean> albnmlists = new ArrayList<>();
    private List<SoundBean> soundlists = new ArrayList<>();
    private List<MvlistBean> mvlists = new ArrayList<>();

    private List<Object> gs = new ArrayList<>();

    private ArrayList<MusicInfo> arraylist = new ArrayList<>();
    private boolean isnofirst;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmnet_find,null);
        return view;
    }

    @Override
    public void onViewCreated(View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    private void initView(View view) {
//        swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
//        swipeRefresh.setColorSchemeColors(ThemeUtils.getColorById(mContext, R.color.theme_color_primary));
//        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        swipeRefresh.setRefreshing(false);
//                    }
//                },1000);
//            }
//        });
        scrollview = (ScrollView) view.findViewById(R.id.scrollview);
        Adloopview = (AdLoopView) view.findViewById(R.id.Adloopview);
        Adloopview.setOnClickListener(new BaseLoopAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(PagerAdapter parent, View view, int position, int realPosition) {
                Toast.makeText(getActivity(), "" + position, Toast.LENGTH_SHORT).show();
            }
        });
        albnm_layout = (RelativeLayout) view.findViewById(R.id.albnm_layout);
        albnm_layout.setOnClickListener(this);
        mv_layout = (RelativeLayout) view.findViewById(R.id.mv_layout);
        mv_layout.setOnClickListener(this);
        sound_layout = (RelativeLayout) view.findViewById(R.id.sound_layout);
        sound_layout.setOnClickListener(this);
        albnmgridview = (MyGridview) view .findViewById(R.id.albnmgridview);
        mvgridview = (MyGridview) view .findViewById(R.id.mvgridview);
        soundgridview = (MyGridview) view .findViewById(R.id.soundgridview);

        albnGridAdapter = new IndexSoundAdapter(getActivity(),albnmlists,true);
        albnmgridview.setAdapter(albnGridAdapter);
        albnmgridview.setOnItemClickListener(this);
        mvGridAdapter = new IndexSoundAdapter(getActivity(),mvlists,true);
        mvgridview.setAdapter(mvGridAdapter);
        mvgridview.setOnItemClickListener(this);
        soundGridAdapter = new IndexSoundAdapter(getActivity(),soundlists,true);
        soundgridview.setAdapter(soundGridAdapter);
        soundgridview.setOnItemClickListener(this);



    }

    private String getLoopDataJson(){
        LooParent mParent = new LooParent();
        List<ItemsEntity> items = new ArrayList<>();
        for(AdverBean bean : advers){
            ItemsEntity itemsEntity = new ItemsEntity();
            itemsEntity.setImgUrl(bean.getImgurl());
            items.add(itemsEntity);
        }
        mParent.setItems(items);
        return new Gson().toJson(mParent);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && !isnofirst){
            relaodAdapter();
            isnofirst = true;
        }
    }

    private void relaodAdapter(){
        new AsyncTask<Void ,Void ,Void >(){

            @Override
            protected Void doInBackground(Void... params) {
                if(NetworkUtils.isConnectInternet(mContext)){
                    isFromCache = false;
                }
                arraylist.clear();
                advers.clear();
                albnmlists.clear();
                mvlists.clear();
                soundlists.clear();
                try{
                    JsonObject list = HttpUtil.getResposeJsonObject(HttpUrl.INDEX);
                    JsonArray mvlist = list.get("mvlist").getAsJsonArray();//mv
                    JsonArray adverlist = list.get("adverlist").getAsJsonArray();//广告
                    JsonArray albnmlist = list.get("albnmlist").getAsJsonArray();//专辑
                    JsonArray soundlist = list.get("soundlist").getAsJsonArray();//声音
                    String msg = list.get("msg").getAsString();
                    for(JsonElement element : adverlist){
                        advers.add(MainApplication.gsonInstance().fromJson(element,AdverBean.class));
                    }
                    for (JsonElement element : albnmlist){
                        albnmlists.add(MainApplication.gsonInstance().fromJson(element,AlbnmlistBean.class));
                    }
                    for(JsonElement element : mvlist){
                        mvlists.add(MainApplication.gsonInstance().fromJson(element,MvlistBean.class));
                    }
                    for(JsonElement element : soundlist){
                        soundlists.add(MainApplication.gsonInstance().fromJson(element,SoundBean.class));
                    }
                    for (int i = 0; i < soundlists.size(); i++) {
                        MusicInfo musicInfo = new MusicInfo();
                        musicInfo.songId = Integer.parseInt(soundlists.get(i).getId());
                        musicInfo.musicName = soundlists.get(i).getSoundname();
                        musicInfo.artist = soundlists.get(i).getSinger();
                        musicInfo.islocal = false;
                        musicInfo.albumName = soundlists.get(i).getSinger();
                        musicInfo.albumId = 2;
                        musicInfo.artistId = 1;
                        musicInfo.lrc = soundlists.get(i).getLyric();
                        musicInfo.albumData = soundlists.get(i).getSoundurlimg();
                        musicInfo.soundurl = soundlists.get(i).getSoundurl();
                        arraylist.add(musicInfo);
                    }

                }catch(Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                LoopData loopData = JsonTool.toBean(getLoopDataJson(),LoopData.class);
                if(loopData.items.size()>0) {
                    Adloopview.refreshData(loopData);
//                    Adloopview.startAutoLoop();
                }
                albnGridAdapter.notifyDataSetChanged();
                soundGridAdapter.notifyDataSetChanged();
                mvGridAdapter.notifyDataSetChanged();
//                scrollview.scrollTo(0,0);
            }
        }.execute();
    }

    Handler handler = new Handler(){

    };

    @Override
    public void onBannerClickListener(int position) {

    }

    public static void setListViewHeightBasedOnChildren(HeightExpandableListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if(parent == albnmgridview){
//            Intent albnIntent = new Intent(getActivity(), NewAlumsDetailActivity.class);
            Intent albnIntent = new Intent(getActivity(), IndexAlbumDetailActivity.class);
            albnIntent.putExtra("albnmlistBean",albnmlists.get(position));
            getActivity().startActivity(albnIntent);
        }else if(parent == mvgridview){
            Intent intent = new Intent(getActivity(),VideoViewActivity.class);
            intent.putExtra("mv",mvlists.get(position));
            getActivity().startActivity(intent);
        }else if(parent == soundgridview){
            HashMap<Long, MusicInfo> infos = new HashMap<Long, MusicInfo>();
            long[] list = new long[1];
            list[0] = arraylist.get(position).songId;
            MusicInfo info = arraylist.get(position);
            infos.put(list[0], info);
            MusicPlayer.addToQueue(mContext, list, arraylist.get(position).songId, infos);
        }

    }

    @Override
    public void onClick(View v) {
        if(v == albnm_layout){
//            Intent intent = new Intent(getActivity(), IndexRecommendActivity.class);
//            intent.putExtra("type",1);
//            intent.putExtra("data",(Serializable) albnmlists);
//            getActivity().startActivity(intent);
            Intent intent = new Intent(getActivity(), IndexItemActivity.class);
            intent.putExtra("type",1);
            intent.putExtra("data",(Serializable) albnmlists);
            getActivity().startActivity(intent);
        }else if(v == mv_layout){
            Intent intent = new Intent(getActivity(), IndexItemActivity.class);
            intent.putExtra("type",2);
            intent.putExtra("data",(Serializable) mvlists);
            getActivity().startActivity(intent);
        }else if(v == sound_layout){
            Intent intent = new Intent(getActivity(), IndexItemActivity.class);
            intent.putExtra("type",3);
            intent.putExtra("data",(Serializable) soundlists);
            getActivity().startActivity(intent);
        }
    }
}
